﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace MediaCenterExractor
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            var title = args[0];
            var sourcePath = args[1];
//            var title = "12.Monkeys.1995.BluRay.x264.720p .YIFY";
//            var sourcePath = @"\\192.168.1.2\Files\Downloads\Done\12 Monkeys (1995)";

                Logger.Create(title);

            Logger.Write("Proccessing Item:");
            Logger.Write(string.Format("Title=\"{0}\"", title));
            Logger.Write(string.Format("Dir=\"{0}\"", sourcePath));
            Logger.Write("=====================\r\n");

            var moviesDestinationBase = ConfigurationManager.AppSettings["MoviesDestinationPath"];
            var seriesDestinationBase = ConfigurationManager.AppSettings["SeriesDestinationPath"];

            string finalPath;

            title = Regex.Replace(title, "[\\(\\[\\{].+?[\\)\\]\\}]", string.Empty).Trim();
            title = title.Replace(' ', '.');


            var match = Regex.Match(title, "(.*)\\.(S\\d\\d)E\\d\\d.*");
            if (match.Success)
            {
                // it's a series
                var seriesName = match.Groups[1].Value.Replace('.',' ');
                var seasson = match.Groups[2].Value;
                finalPath = Path.Combine(seriesDestinationBase, Path.Combine(seriesName, seasson));
            }
            else
            {
                // it's a movie
                finalPath = Path.Combine(moviesDestinationBase, title);
            }

            if (Directory.Exists(sourcePath))
            {
                Logger.Write(string.Format("Destination: \"{0}\"", finalPath));

                var success = SubtitlesHandler.LoadSubtitles(title, finalPath);
                if (success)
                {
                    Logger.Write("Found subtitles, handling file..");
                    MediaFilesHandler.HandleFiles(sourcePath, finalPath);
                }
                else
                {
                    Logger.Write("WARN: Subtitles wasn't found, did not handle the file..");
                }
            }
            else
            {
                Logger.Write("ERROR: Source path does not exist");
            }

            Logger.Write("COMPLETED.");
        }
    }
}
